package com.briup.estore.userAPI.web.listener;


import com.briup.estore.common.util.DateUtil;
import com.briup.estore.common.util.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.Objects;

/**
 * @author adam
 * @date 2023/5/15
 */
@Component
public class SessionListener implements HttpSessionListener {
    @Autowired
    private RedisCache redisCache;

    @Override
    public void sessionCreated(HttpSessionEvent se) {
        //当前在线人数
        Object o = redisCache.getCacheObject(DateUtil.getNowDate() + ":online") ;
        Integer online = Objects.isNull(o) ? 0 : (Integer) o;
        redisCache.setCacheObject("online", ++online);
        // 访客数
        Object o1 = redisCache.getCacheObject("visitors");
        Integer  visitors=Objects.isNull(o1)?0: (Integer) o1;
        redisCache.setCacheObject("visitors",++visitors);

    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        Integer online = redisCache.getCacheObject("online");
        if (Objects.isNull(online)) {
            return;
        }
        redisCache.setCacheObject("online", online - 1);
    }
}
